var app = getApp();
//声明全局变量
let proListToTop = [],
    menuToTop = [],
    MENU = 0,
    windowHeight, timeoutId;
// MENU ==> 是否为点击左侧进行滚动的，如果是，则不需要再次设置左侧的激活状态
import api from '../../../utils/api.js'
var app = getApp();
var QQMapWX = require("../../../utils/qqmap-wx-jssdk.js");
var qqmapsdk;
import { HTTP } from '../../../utils/http.js'
import utils from '../../../utils/util.js'
import { config } from '../../../utils/config'

let http = new HTTP()

Page({

    data: {
        staticImg: app.globalData.staticImg,
        currentActiveIndex: 0,
        currentCookIndex: 0,
        imgUrl: config.imgUrl,
        inputValue: '',
        categoryActive: 1,
        searchTip: false,
        categoryBar: [
            { cateName: '菜品分类', cateId: '1' },
            { cateName: '菜谱分类', cateId: '2' }
        ],
        searchObj: {
            searchBg: "#fff",
            placeStr: '请输入菜品名称',
            inputValue: ''
        }

    },
    onLoad: function (e) {
        let that = this
        /*获取高度*/
        this.getAllRects();
        /*获取菜品一级分类*/
        this.getInfo(api.getOneCategories, "GET", {}).then(res => {
            that.setData({
                category: res
            })
            this.getCategoryList(res[0].id, 0)
        })

        /*获取菜谱一级分类*/
        this.getInfo(api.getAllCookCate, "GET", {}, false).then((res) => {
            that.setData({
                cookCategory: res
            })
        })

    },
    /*切换菜品分类*/
    changeCate(e) {
        let cateId = e.currentTarget.dataset.id;
        this.setData({
            categoryActive: cateId
        })
        let searchObj = this.data.searchObj;
        if (cateId == 2) {

            searchObj.placeStr = '请输入菜谱名称'
            this.setData({
                // currentCookIndex: 0,
                // rightProTop: 0,
                searchObj
            })
            this.getprotop();
        }
        if (cateId == 1) {
            searchObj.placeStr = '请输入菜品名称'
            this.setData({
                searchObj
            })
        }



    },

    /*获取菜品一级分类*/
    getInfo(url, method, data, loadding = true) {
        return new Promise((resolve, reject) => {
            if (loadding) {
                wx.showLoading({
                    title: '加载中...',
                })
            }

            http.request({
                url: url,
                method: method,
                data: data,
                success: res => {
                    if (res.msg && res.error_code) {
                        wx.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 1500
                        });
                        return;
                    }
                    if (res.code == 200) {
                        resolve(res.data);
                    }
                    if (loadding) {
                        wx.hideLoading()
                    }

                },
                fail: () => { },
                complete: () => {
                    wx.hideLoading()
                }


            })
        })
    },

    /*搜索按钮*/
    searchHandle(e) {
        let inputValue = e.detail.inputValue
        this.setData({
            inputValue
        })
        /* categoryActive 1菜品   2菜谱    */
        if (this.data.categoryActive == 1) {
            wx.navigateTo({
                url: '/pages/classify/searchVege/searchVege?kw=' + inputValue
            })
        }
        console.log(this.data.categoryActive);
        if (this.data.categoryActive == 2) {
            wx.navigateTo({
                url: '/pages/classify/searchCook/searchCook?kw=' + inputValue
            })
        }
    },
    onShow() {
        wx.wg_util.refreshShopCarBadge();
        // 父组件调用子组件方法
        this.search = this.selectComponent('#search');
        this.search.deleteSearch();
    },
    changeMenuCate(e) {
        let that = this
        let id = e.currentTarget.dataset.id;
        let index = e.currentTarget.dataset.index;
        this.setData({
            currentActiveIndex: index,
            caipinProTop: 0,
        })

        this.getCategoryList(id, index);
        // proListToTop = [];

    },
    changeMenu(e) {
        let index = e.currentTarget.dataset.index;
        console.log(proListToTop);
        // 改变左侧tab栏操作
        if (index === this.data.currentCookIndex) return
        MENU = 1
        this.setData({
            currentCookIndex: index,
            rightProTop: proListToTop[index]
        })
        this.setMenuAnimation(index)

    },
    getCategoryList(id, index) {
        let that = this
        // this.setMenuAnimation(Number(e.target.id);
        let address = wx.getStorageSync('address');
        let data = {
            lat: address.latitude,
            lng: address.longitude,
            id: id
        }
        this.getInfo(api.getTwoCategories, "GET", data, true).then(res => {
            that.setData({
                vegeList: []
            })
            setTimeout(() => {
                that.setData({
                    vegeList: res,
                    currentActiveIndex: index,
                })
            }, 0);

        }).then(() => {
            console.log(index);

            // this.getprotop(index)
        })

    },
    getCookgoryInfo(id, index, loadding) {
        let that = this
        this.getInfo(api.getCookgoryInfo, "GET", { id }, loadding).then(res => {
            that.setData({
                cookList: res,
                currentCookIndex: index
            })
        }).then(() => {
            console.log(index);
            // this.getprotop(index)
        })
    },
    vegeList(e) {
        let id = e.currentTarget.dataset.id
        let name = e.currentTarget.dataset.name
        wx.navigateTo({
            url: '/pages/classify/vegeList/vegeList?id=' + id + '&name=' + name
        })
    },
    addBasket(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/classify/addBasket/addBasket?id=' + id
        })
    },
    viewDite(e) {
        console.log(2222);

        let id = e.currentTarget.dataset.id;
        let pid = e.currentTarget.dataset.pid
        wx.navigateTo({
            url: '/pages/classify/diet/diet?id=' + id + '&pid=' + pid
        })
    },
    scroll(e) {
        // console.log(e);
        for (let i = 0; i < proListToTop.length; i++) {
            if (e.detail.scrollTop < (proListToTop[i] - 100) && i !== 0 && e.detail.scrollTop > (proListToTop[i - 1] - 100)) {
                return this.setDis(i)
            }
        }
        // 找不到匹配项，默认显示第一个数据
        if (!MENU) {
            this.setData({
                currentCookIndex: 0
            })
        }
        MENU = 0
    },

    setDis(i) {
        // 设置左侧menu栏的选中状态
        console.log('----', i);

        if (i !== this.data.currentCookIndex + 1 && !MENU) {
            this.setData({
                currentCookIndex: i - 1
            })
        }
        MENU = 0
        this.setMenuAnimation(i)
    },
    setMenuAnimation(i) {
        // 设置动画，使menu滚动到指定位置。
        let self = this
        console.log(33)
        if (menuToTop[i].animate) {
            console.log(11111)
            // 节流操作
            if (timeoutId) {
                clearTimeout(timeoutId)
            }
            timeoutId = setTimeout(() => {
                console.log(12138)
                self.setData({
                    leftMenuTop: (menuToTop[i].top - windowHeight)
                })
            }, 50)
        } else {
            console.log(11)
            if (this.data.leftMenuTop === 0) return
            console.log(22)
            this.setData({
                leftMenuTop: 0
            })
        }
    },
    getActiveReacts() {
        wx.createSelectorQuery().selectAll('.menu-active').boundingClientRect(function (rects) {
            return rects[0].top
        }).exec()
    },
    getAllRects() {
        let that = this

        //获取搜索框底部与头部的距离
        wx.createSelectorQuery().selectAll('.tui-fixed-left').boundingClientRect(function (rects) {
            rects.forEach(function (rects) {
                that.setData({
                    searchBottom: rects.top
                })
            })
        }).exec()

        // 获取商品数组的位置信息


    },

    getprotop() {
        let that = this

        // 获取menu数组的位置信息
        wx.createSelectorQuery().selectAll('.menu-item').boundingClientRect(function (rects) {
            wx.getSystemInfo({
                success: function (res) {
                    console.log(res);
                    windowHeight = res.windowHeight / 2
                    console.log(windowHeight)
                    rects.forEach(function (rect) {
                        menuToTop.push({
                            top: rect.top,
                            animate: rect.top > windowHeight
                        })
                    })
                }
            })
        }).exec()

        if (proListToTop.length < 1) {
            wx.createSelectorQuery().selectAll('.pro-item').boundingClientRect(function (rects) {
                console.log('rects', rects)
                rects.forEach(function (rect) {
                    // console.log('rect.top', rect.top)
                    // 这里减去44是根据你的滚动区域距离头部的高度，如果没有高度，可以将其删去
                    proListToTop.push(rect.top - that.data.searchBottom)
                })
            }).exec()

            console.log('proListToTop', proListToTop);
        }


    },
    // 获取系统的高度信息
    getSystemInfo() {
        let self = this
        wx.getSystemInfo({
            success: function (res) {
                windowHeight = res.windowHeight / 2
            }
        })
    },


})